import re
import subprocess
import sys
import tempfile


def Ping(raw_destination):
    assert type(raw_destination) is str
    destination = raw_destination.split('.')
    if len(destination) == 4:
        for i in destination:
            assert type(eval(i)) is int
    elif len(destination) == 3:
        for i in destination:
            assert re.match(r'[\w\\:/]+', i)
        raw_destination = destination[0].split("//")[-1] + '.' + destination[1] + '.' + destination[2].split("/")[0]
    wrong = True
    ttl = None
    if 'win' not in sys.platform or 'darwin' in sys.platform:
        out_temp = tempfile.SpooledTemporaryFile()
        fileno = out_temp.fileno()
        ex = subprocess.Popen('ping %s -c4' % raw_destination, stdout=fileno, stderr=fileno, shell=True)
        ex.wait(5)
        out_temp.seek(0)
        lines = out_temp.readlines()

        for i in lines:
            print(i)
        lines = str(lines)
        # out, err = ex.communicate()
        wrong = re.findall(r'Request\stimed\sout', lines)
        ttl = re.findall(r'ttl=\d+', lines)
    else:
        out_temp = tempfile.SpooledTemporaryFile()
        fileno = out_temp.fileno()
        ex = subprocess.Popen('ping %s' % raw_destination, stdout=fileno, stderr=fileno, shell=True)
        ex.wait()
        out_temp.seek()
        lines = out_temp.readlines()
        for i in lines:
            print(i)
            lines[lines.index(i)] = i.decode('gbk')
        lines = str(lines)
        wrong = re.findall(r'找不到主机', lines)
        ttl = re.findall(r'TTL=\d+', lines)

    if not wrong and ttl:
        return True
    else:
        return False
